<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>4-4实现购物车的几个功能</title>
    <script src="https://unpkg.com/vue@3"></script>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="app">
        <div v-if="books.length>0">
            <table>
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>书籍名称</th>
                        <th>出版日期</th>
                        <th>价格</th>
                        <th>购买数量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="item in books">
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.date}}</td>
                        <td>{{'￥'+item.price.toFixed(2)}}</td>
                        <td>
                            <button @click="item.num++">+</button>
                            <span>{{item.num}}</span>
                            <button @click="item.num--">-</button>
                        </td>
                        <td><button @click="remove(item.id)">移除</button></td>
                    </tr>
                </tbody>
            </table>
            <h3>总价格：{{ sum.toFixed(2) }}</h3>
        </div>
        <div v-else>
            <h3>购物车为空</h3>
        </div>

    </div>
    <script>
        const { createApp } = Vue;
        createApp({
            data() {
                return {
                    books: [
                        { id: 1, name: "《JavaScript程序设计》", date: "2022-9", price: 85.00, num: 1 },
                        { id: 2, name: "《C语言基础》", date: "2021-2", price: 59.00, num: 1 },
                        { id: 3, name: "《Java高级语言编程》", date: "2022-10", price: 39.00, num: 1 },
                        { id: 4, name: "《数据库原理》", date: "2023-3", price: 128.00, num: 1 },
                        { id: 5, name: "《计算机网络》", date: "2022-8", price: 88.00, num: 1 },
                    ],
                };
            },
            methods: {
                remove(id) {
                    this.books = this.books.filter(function (item) {
                        return item.id != id;
                    })
                }
            },
            computed: {
                sum() {
                    let res = 0;
                    for (let i = 0; i < this.books.length; i++)
                        res += this.books[i].price * this.books[i].num;
                    return res;
                }
            }
        }).mount("#app");
    </script>
</body>

</html>